package com.infitecs.eyas.develop.service;


import com.infitecs.krill.util.FileUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

@Service
@Lazy(false)
public class I18NService implements ServletContextAware {

    private ServletContext servletContext;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    @PostConstruct
    public void initJsI18N() throws IOException {
        if (servletContext != null) {
            String jsPath = servletContext.getRealPath("/js");
            File viewMessagesDir = new File(servletContext.getRealPath("/WEB-INF/classes/ViewMessages"));
            File[] files = viewMessagesDir.listFiles();
            if (files != null) {
                for (File viewMessage : files) {
                    Resource resource = new ClassPathResource("/ViewMessages/" + viewMessage.getName());
                    Properties props = PropertiesLoaderUtils.loadProperties(resource);
                    StringBuilder jsString = new StringBuilder("i18n = {");
                    for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) {
                        String key = (String) e.nextElement();
                        jsString.append("\"").append(key).append("\":\"").append(props.getProperty(key)).append("\",");
                    }
                    jsString.deleteCharAt(jsString.lastIndexOf(",")).append("}");
                    FileUtil.createFile(viewMessage.getName().replace(".properties", ".js"), jsString.toString(), jsPath);
                }
            }
        }
    }

    public static String getResourceBundleString(HttpSession session, String msgString) {
        return null;
    }
}
